package com.freshdirect.src.controller;

import com.freshdirect.src.model.ShoppingCart;
import com.freshdirect.src.model.User;
import com.freshdirect.src.service.ShoppingCartService;
import com.freshdirect.src.service.UserService;
import java.io.IOException;
import java.text.DateFormat;
import java.util.Date;
import java.util.Locale;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;


/**
 * Handles requests for the application home page.
 */
@Controller
public class HomeController {
	
	private static final Logger logger = LoggerFactory.getLogger(HomeController.class);
	
	/**
	 * Simply selects the home view to render by returning its name.
	 */
	@RequestMapping(value = "/", method = RequestMethod.GET)
	public String home(Locale locale, Model model, HttpSession session) {
		logger.info("Welcome home! The client locale is {}.", locale);
		
		Date date = new Date();
		DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG, locale);
		
		String formattedDate = dateFormat.format(date);
		
		model.addAttribute("serverTime", formattedDate);
                if(session.getAttribute("cart")!=null){
                        ShoppingCart cart = (ShoppingCart)session.getAttribute("cart");
                        ShoppingCartService scs= new ShoppingCartService();
                        cart = scs.checkAvailability(cart);
                        session.setAttribute("cart", cart);
                        model.addAttribute("cart",session.getAttribute("cart"));
               }
		return "home";
	}
        
         @RequestMapping(value="/signup", method=RequestMethod.GET)
    public String signup(Model model) {
       
 User user = new User();
        model.addAttribute("userForm", user);
                return "signup";
        }
 
            
        @RequestMapping(value="/signup",method = RequestMethod.POST)
    public String processRegistration( @Valid @ModelAttribute("userForm") User userForm,
            BindingResult result,Model model) {
       
      if (result.hasErrors()) {
            return "signup";
        }
      else{
          UserService userService= new UserService();
        userService.saveUser(userForm);
        String result_s =  userForm.getResult();
        if(result_s.equals("Please Change Username")){
            model.addAttribute("result",result_s);
            return "signup";
        }
        else{

       model.addAttribute("userName", userForm.getUserName());
        model.addAttribute("result", userForm.getResult());
 
        return "RegistrationSuccess";}
        }
    }
	
     @RequestMapping(value="/user", method=RequestMethod.POST)
    public String processLogin(HttpServletRequest request, HttpServletResponse response,Model model,User user,HttpSession session) throws IOException
 {
        String userName=request.getParameter("userName");
        String password=request.getParameter("password");
        model.addAttribute("userName",userName);
        model.addAttribute("password",password);
       UserService userService= new UserService();
        userService.login(user);
     
        if(user.getResult().equals("Wrong Username or Password")){
        request.getSession().setAttribute("login","Wrong Username or Password");
        response.sendRedirect(request.getContextPath());
        return null;   
        }else{
        request.getSession().invalidate();
        request.getSession().setAttribute("userName",user.getUserName());
        request.getSession().setAttribute("userID",user.getId());
        response.sendRedirect(request.getContextPath());
               return null;
        }               
        
    }
    
    
    @RequestMapping(value="/userout", method=RequestMethod.GET)
    public String processLogout(HttpServletRequest request, HttpServletResponse response,HttpSession session) throws IOException
 {
     request.getSession().invalidate();
      response.sendRedirect(request.getContextPath());
      return null;   
}
}